package com.fy.module.repo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fy.common.dto.PageDto;
import com.fy.common.dto.PageResult;
import com.fy.common.exception.ServiceException;
import com.fy.common.vo.ApiRest;
import com.fy.module.repo.entity.Repo;
import com.fy.module.repo.mapper.RepoMapper;
import com.fy.module.repo.service.IRepoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 题库 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2023-03-18
 */
@Service
public class RepoServiceImpl extends ServiceImpl<RepoMapper, Repo> implements IRepoService {

    @Autowired
    private RepoMapper repoMapper;

    //分页查询所有题库
    @Override
    public PageResult<Repo> selectRepoByPages(PageDto<Repo> pageDto) {
        //处理请求参数
        if (pageDto == null) {
            throw new ServiceException("分页数据不能为空");
        }
        //判断当前页是否为空
        if (pageDto.getNow()<=0) {
            throw new ServiceException("当前页数据不能为空");
        }
        //判断每页显示条数是否为空，为空就默认设置每页默认显示条数为5
        if (pageDto.getSize()<=0) {
            pageDto.setSize(5);
        }
        //判断查询条件是否为空
        if (pageDto.getWhere() == null) {
            throw new ServiceException("查询条件不能为空");
        }

        //设置分页
        IPage<Repo> page=new Page<>(pageDto.getNow(), pageDto.getSize());
        //条件构造器查询
        QueryWrapper<Repo> queryWrap=new QueryWrapper();
        if(pageDto.getWhere().getTitle()!=null) {
            queryWrap.like("title", pageDto.getWhere().getTitle());
        }



//        IPage pageInfo=this.page(page,queryWrap);
        IPage<Repo> pageInfo = repoMapper.selectPage(page, queryWrap);
        System.out.println("=====>"+pageInfo.getRecords());

        PageResult pageResult=new PageResult();
        pageResult.setPages(pageInfo.getPages());
        pageResult.setList(pageInfo.getRecords());
        pageResult.setTotal(pageInfo.getTotal());

        return pageResult;
    }


    /**
     *添加题库
     */
    @Override
    public ApiRest insertRepo(Repo repo) {
        if (repo == null) {
            throw new ServiceException("要添加的数据不能为空");
        }
        repo.setId(IdWorker.getIdStr());
        repo.setCreateTime(new Date());
        repo.setUpdateTime(new Date());
        repo.setIsDelete(0);
        boolean b = this.save(repo);
        if (b){
            return ApiRest.success();
        }
        return ApiRest.failure();
    }

}
